package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Resource
    private SpecParamService specParamService;

    //根据商品分类id，查询规格组及组内参数
    @Override
    public List<SpecGroupDTO> querySpecList(Long id) {
        //先查规格组
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(query().eq("category_id", id).list());
        //再查规格参数
        List<SpecParamDTO> paramDTOList = specParamService.querySpecParams(id, null, null);
        //查到的是无序的规格参数，先将参数按groupId分组
        Map<Long, List<SpecParamDTO>> map = paramDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //将参数放到规格组
        for (SpecGroupDTO specGroupDTO : groupDTOList) {
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        }
        return groupDTOList;
    }
}
